<template>

    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form ref="queryFormRef" :inline="true" :model="paramsData" class="-mb-10px" label-width="68px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="paramsData.name" class="!w-300px" clearable placeholder="姓名" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="paramsData.phone" class="!w-300px" clearable placeholder="请输入手机号"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="paramsData.idCard" class="!w-300px" clearable placeholder="请输入身份证号"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="paramsData.status" class="!w-300px" clearable placeholder="请选择状态">
            <el-option v-for="item in statusList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-hasPermi="['wise:employee:query']" @click="handleQuery">
            <Icon class="mr-5px" icon="ep:search" />
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon class="mr-5px" icon="ep:refresh" />
            重置
          </el-button>
          <el-button v-hasPermi="['wise:employee:create']" plain type="primary" @click="openForm(1)">
            <Icon class="mr-5px" icon="ep:plus" />
            新增
          </el-button>
          <el-button v-hasPermi="['wise:employee:export']" :loading="exportLoading" plain type="success"
            @click="handleExport">
            <Icon class="mr-5px" icon="ep:download" />
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>
  
    <!-- 列表 -->
    <ContentWrap>
      <el-table v-loading="loading" :data="tableData" @selection-change="tableSelectionChange">
        <el-table-column type="selection" width="30" />
        <template v-for="item in tableColumn" :key="item.prop">
          <el-table-column
            :width="item.width"
            :align="item.align ? item.align : 'center'" 
            :label="item.label"
            :prop="item.prop"
          >
            <template #default="scope">
              <div v-if="item.prop == 'status'">
                <el-tag type="info" v-if="scope.row.status == 0">离职</el-tag>
                <el-tag type="warning" v-else-if="scope.row.status == 1">留职</el-tag>
                <el-tag type="success" v-else-if="scope.row.status == 2">在职</el-tag>
                <span v-else>-</span>
              </div>
              <div v-else-if="item.prop == 'skillName'">
                <div v-if="scope.row.skillName">{{ scope.row.skillName }}</div>
                <div v-else>-</div>
              </div>
              <div v-else-if="item.prop == 'createTime'">
                <p>创建时间：{{ scope.row.createTime ? formatDate(scope.row.createTime) : '-' }}</p>
                <p>更新时间：{{ scope.row.updateTime ? formatDate(scope.row.updateTime) : '-' }}</p>
              </div>
              <div v-else-if="item.prop == 'creator'">
                <p>创建：{{ scope.row.creator ? scope.row.creator : '-' }}</p>
                <p>更新：{{ scope.row.updater ? scope.row.updater : '-' }}</p>
              </div>
              <div v-else>
                {{ scope.row[item.prop] || '-' }}
              </div>
            </template>
          </el-table-column>
        </template>
  
        <el-table-column :width="200" align="center" label="操作">
          <template #default="scope">
            <el-button v-hasPermi="['wise:employee:update']" link type="primary" @click="openForm(2, scope.row.id)">
              编辑
            </el-button>
            <el-button  v-hasPermi="['wise:employee:update-status']" link type="primary" @click="openStatus(scope.row)">
              状态
            </el-button>
            <el-button v-hasPermi="['wise:employee:delete']" link type="danger" @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
  
      </el-table>
  
  
      <!-- 分页 -->
      <Pagination v-model:limit="paramsData.pageSize" v-model:page="paramsData.pageNo" :total="total" @pagination="getList" />
    </ContentWrap>

  <StatusForm ref="StatusFormRef" />

</template>
<script setup>
import * as PersonnelApi from '@/api/system/personnel'
import { ref, reactive, inject } from "vue"
import { useI18n } from 'vue-i18n'
import { formatDate } from '@/utils/formatTime' // 时间戳转日期
import StatusForm from './statusForm.vue'
import download from '@/utils/download'
let setPageStatus = inject('setPageStatus', () => {});

const paramsData = reactive({
  pageNo: 1,
  pageSize: 10,
  name: null,
  phone: null,
  idCard: null,
  userType: 1,
  status: undefined,
  ids: []
})
const statusList = reactive([
  { name: '离职', id: 0 },
  { name: '留职', id: 1 },
  { name: '在职', id: 2 },
])
const StatusFormRef = ref(null)

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const tableData = ref([]) // 列表的数据
const tableColumn = ref([
  { prop: 'name', label: '姓名', align: 'center', },
  { prop: 'phone', label: '联系电话', align: 'center'},
  { prop: 'idCard', label: '身份证号', align: 'center',},
  { prop: 'skillName', label: '工种', align: 'center'},
  { prop: 'entryTime', label: '入职时间', align: 'center'},
  { prop: 'status', label: '状态', align: 'center'},
  { prop: 'createTime', label: '时间', align: 'center', width: 240},
  { prop: 'creator', label: '操作人', align: 'center', width: 240},
]) // 表格的列
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const selectIds = ref([])

/** 查询角色列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await PersonnelApi.getPersonnelList(paramsData)

    data.list.forEach(item => {
      let skillName = []
      if (item.skills && item.skills.length > 0) {
        item.skills.forEach(curr => {
          skillName.push(curr.jobType)
        })  
        item.skillName = skillName.join('/')
      }else{
        item.skillName = ''
      }
    })

    tableData.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
provide('getList', getList)

/**
 * 表单验证 - 开始
 * */ 
const formRules = reactive({
  name: [{ required: true, message: '字典名称不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '字典类型不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref
/**
 * 表单验证 - 结束
 * */

/** 搜索按钮操作 */
const handleQuery = () => {
  paramsData.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const openForm = (type, id) => {
  setPageStatus(2, type, id)
}

const openStatus = (row) => {
  const {id, status} = row
  console.log(id, status, row);
  StatusFormRef.value?.init(id, status)
}

/** 删除按钮操作 */
const handleDelete = async (id) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await PersonnelApi.deletePersonnel(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}




const tableSelectionChange = (selection) => {
  selectIds.value = selection.map(item => item.id)
}


const handleExport = async () => {
  if(selectIds.value.length > 0){
    paramsData.ids = selectIds.value
  }
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await PersonnelApi.exportPersonnel(paramsData)
    download.excel(data, '劳务员工列表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
<style lang="scss" scoped></style>
